package com.pfzy.lib.net.interceptor;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pfzy.lib.config.ConstValue;
import com.pfzy.lib.config.DTO.DriverLogin;
//import com.pfzy.lib.config.UserConfig;
import com.pfzy.lib.config.log.MyLog;
import com.pfzy.lib.net.SignStruct;
import com.pfzy.lib.net.utils.AesUtil;
import com.pfzy.lib.net.utils.RsaUtil;
import com.pfzy.lib.sdk.log.UXLog;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

/**
 * 网络请求拦截
 */
public class RequestInterceptor implements Interceptor {
    private String encryptKey = null;

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        String url = request.url().toString();
        String method = request.method();

        if ("POST" == method) {
            RequestBody body = request.body();
            HttpUrl.Builder builder = request.url().newBuilder();

            // 将原body写入缓存
            Buffer buffer = new Buffer();
            body.writeTo(buffer);
            Request.Builder reqBuilder = request.newBuilder();
            // 未加密的请求参数
            String requestData = URLDecoder.decode(buffer.readString(StandardCharsets.UTF_8), "utf-8");
            _logd( "requestData: " + requestData);

            String aesKey = AesUtil.getKey();
            String data = null;
            try {
                data = AesUtil.encrypt(requestData, aesKey);
                _logd( "AES 加密: " + data);
            } catch (Exception e) {
                e.printStackTrace();
            }

            HashMap<String, String> map = new HashMap<>();
            map.put("data", data);
            Gson gson = new GsonBuilder().disableHtmlEscaping().create();
            String json = gson.toJson(map);

            Long time = System.currentTimeMillis();
            SignStruct signStruct = new SignStruct();
            signStruct.setAesKey(aesKey);
            signStruct.setTime(time);
            _logd("signStruct: " + signStruct.toString());

            String sign = null;
            try {
                sign = RsaUtil.encryptByPublicKey(signStruct.toString(), encryptKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
            _logd( "RSA 加密: " + sign);

            String token = ConstValue.getToken();
            if (token != null) {
                _logd( "AuthToken: " + token);
            } else {
                _logd( "AuthToken is Null");
            }

            // 新的请求体
            RequestBody newRequestBody = null;
            try {
                // 可在这对请求参数加密后重新发起请求
                newRequestBody = RequestBody.create(body.contentType(), json);

                if (token != null) {
                    Request newRequest = reqBuilder
                            .addHeader("Sign", sign)
                            .addHeader("AuthToken", token)
                            .post(newRequestBody)
                            .url(builder.build())
                            .build();
                    return chain.proceed(newRequest);
                } else {
                    Request newRequest = reqBuilder
                            .addHeader("Sign", sign)
                            .post(newRequestBody)
                            .url(builder.build())
                            .build();
                    return chain.proceed(newRequest);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return chain.proceed(request);
    }

    public void setEncryptKey(String key) {
        encryptKey = key;
    }

    private void _logd(String msg) {
        MyLog.logd("RequestInterceptor: " + msg);
    }
}
